package com.example.picturebacked.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.example.picturebacked.exception.BusinessException;
import com.example.picturebacked.exception.ErrorCode;
import com.example.picturebacked.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * @Autheor LBT
 */
@Service
public class URLPictureUpload extends PictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File temp) throws Exception {
        String fileURL = (String) inputSource;
        HttpUtil.downloadFile(fileURL, temp);

    }

    @Override
    protected String getOriginalFilename(Object inputSource) {
        String fileURL = (String) inputSource;
        return FileUtil.mainName(fileURL);
    }

    @Override
    protected void vaildPicture(Object inputSource) {
        String fileURL = (String) inputSource;
        ThrowUtils.throwIf(fileURL == null, ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        // 1、验证格式
        try {
            new URL(fileURL);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
        }
        // 2、校验 URL 协议
        ThrowUtils.throwIf(!fileURL.startsWith("http://") && !fileURL.startsWith("https://"),
                ErrorCode.PARAMS_ERROR, "文件地址协议错误");

        // 3、通过发送 HEAD 请求验证文件是否存在

        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, fileURL).execute();
            // 不直接抛出异常的原因: 因为有可能目标网站不支持head请求
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4、 校验文件类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_TYPE_LIST = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_TYPE_LIST.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }

            // 5、校验文件大小
            String contentLenghtStr = response.header("Content-Lenght");

            if (StrUtil.isNotBlank(contentLenghtStr)) {
                try {
                    // 使用Long.parseLong()将字符串转为 long，判断上传的文件大小是否超过2MB
                    long contentLenght = Long.parseLong(contentLenghtStr);
                    final long ONE_MB = 1024 * 1024;
                    ThrowUtils.throwIf(contentLenght > 2 * (ONE_MB), ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}
